$(function () {
  const account = new Account()
  account.getUserInfo((err, userInfo) => {
    if (!err) {
      console.log('已经登录')
      console.log(userInfo)
      window.userInfo = userInfo
      $('#nickname').val(userInfo.nickname || '')
      $('#birthday').val(userInfo.birthday || '')
      if ($('#birthday').val()) {
        $('.age-group label[for="birthday"]').text(`${getAge($('#birthday').val())}岁`)
      } else {
        $('.age-group label[for="birthday"]').text('请选择孩子年龄')
      }
      if (userInfo.gender === 2) {
        $('.sex-group #girl').attr('checked', true)
        $('.sex-group #boy').attr('checked', null)
      } else {
        $('.sex-group #boy').attr('checked', true)
        $('.sex-group #girl').attr('checked', null)
      }
      if (!userInfo.isPasswordSet) {
        // 没设置密码 弹用户资料和密码
        $('.survey').hide()
        $('.class-time').hide()
        $('.user-info').show()
        $('.mask').show()
      } else {
        if (!(userInfo.nickname && userInfo.birthday)) {
          // 有设置密码 但没用户资料 弹用户资料 但不弹密码
          $('.survey').hide()
          $('.class-time').hide()
          $('.user-info .pwd-group').hide()
          $('.user-info').show()
          $('.mask').show()
        } else {
          if (!userInfo.timeTable) {
            // 没有上课时间 弹上课时间
            $('.survey').hide()
            $('.user-info').hide()
            $('.class-time').show()
            $('.mask').show()
          } else {
            if (!(userInfo.survey || userInfo.level > 0)) {
              // 没有问卷调查 弹问卷调查
              $('.user-info').hide()
              $('.class-time').hide()
              $('.survey').show()
              $('.mask').show()
            }
          }
        }
      }
    } else {
      console.log('没有登录')
    }
  })

  // 随机生成nickname
  $('.nickname-group .random').off('click').on('click', e => {
    $('#nickname').val(randomName(parseInt($(`input[name="sex"]:checked`).val())))
  })

  // 选择出生日期生成年龄
  $('#birthday').off('input change').on('input change', e => {
    if ($('#birthday').val()) {
      $('.age-group label[for="birthday"]').text(`${getAge($('#birthday').val())}岁`)
    } else {
      $('.age-group label[for="birthday"]').text('请选择孩子年龄')
    }
  })

  // 上课时间 选择每周2节或者3节课
  $('input[name="weeken"]').off('input change').on('input change', e => {
    const weeken = parseInt($(`input[name="weeken"]:checked`).val())
    console.log(weeken)
    if (weeken === 2) {
      $('#frequency2').show()
      $('#frequency3').hide()
    } else {
      $('#frequency2').hide()
      $('#frequency3').show()
    }
  })

  // 根据出生年月生成年龄
  function getAge (strBirthday) {
    var returnAge
    var strBirthdayArr = strBirthday.split('-')
    var birthYear = strBirthdayArr[0]
    var birthMonth = strBirthdayArr[1]
    var birthDay = strBirthdayArr[2]

    var d = new Date()
    var nowYear = d.getFullYear()
    var nowMonth = d.getMonth() + 1
    var nowDay = d.getDate()

    if (nowYear == birthYear) {
      returnAge = 0//同年 则为0岁
    } else {
      var ageDiff = nowYear - birthYear //年之差
      if (ageDiff > 0) {
        if (nowMonth == birthMonth) {
          var dayDiff = nowDay - birthDay//日之差
          if (dayDiff < 0) {
            returnAge = ageDiff - 1
          } else {
            returnAge = ageDiff
          }
        } else {
          var monthDiff = nowMonth - birthMonth//月之差
          if (monthDiff < 0) {
            returnAge = ageDiff - 1
          } else {
            returnAge = ageDiff
          }
        }
      } else {
        returnAge = -1//返回-1 表示出生日期输入错误 晚于今天
      }
    }
    return returnAge//返回周岁年龄
  }

  // 提交用户资料
  $('#updateUserProfile').off('click').on('click', e => {
    const nickname = $('#nickname').val() || ''
    const birthday = $('#birthday').val() || ''
    const gender = parseInt($(`input[name="sex"]:checked`).val())
    const password = $('#password').val() || ''
    if (!nickname) {
      utils.toast('昵称不能为空')
      return
    }
    if (!birthday) {
      utils.toast('生日不能为空')
      return
    }
    userInfo.nickname = nickname
    userInfo.birthday = birthday
    userInfo.gender = gender
    account.ajax({
      type: 'POST',
      path: `/s/user/`,
      data: {
        nickname,
        gender,
        birthday,
      },
      success: result => {
        if (!userInfo.isPasswordSet) {
          if (password.length >= 6 &&
            password.length <= 12 &&
            /^[0-9a-zA-Z]*$/.test(password)) {
            account.ajax({
              type: 'POST',
              path: `/s/user/password`,
              data: {password},
              success: data => {
                next()
              },
              error: err => {
                const error = JSON.parse(err.response)
                console.error(error.message)
              }
            })
          } else {
            utils.toast('密码格式不正确')
            return
          }
        } else {
          next()
        }
      },
      error: err => {
        const error = JSON.parse(err.response)
        console.error(error.message)
      }
    })

    function next () {
      $('.user-info').hide()
      $('.class-time').hide()
      $('.survey').hide()
      $('.mask').hide()
      if (!userInfo.timeTable) {
        // 没有上课时间 弹上课时间
        $('.survey').hide()
        $('.user-info').hide()
        $('.class-time').show()
        $('.mask').show()
      } else {
        if (!(userInfo.survey || userInfo.level > 0)) {
          // 没有问卷调查 弹问卷调查
          $('.user-info').hide()
          $('.class-time').hide()
          $('.survey').show()
          $('.mask').show()
        }
      }
    }
  })

  // 提交上课时间
  $('#submitClassTime').off('click').on('click', e => {
    const type = parseInt($(`input[name="weeken"]:checked`).val())
    const time = $(`input[name="time"]:checked`).val()
    const frequency = {}
    $(`input[name="frequency${type}"]:checked`).val().split('_').forEach(f => {
      frequency[`${f}_${time}`] = 1
    })
    account.ajax({
      type: 'PUT',
      path: `/s/user/timeTable`,
      data: frequency,
      success: result => {
        next()
      },
      error: err => {
        const error = JSON.parse(err.response)
        console.error(error.message)
      }
    })

    function next () {
      $('.user-info').hide()
      $('.class-time').hide()
      $('.survey').hide()
      $('.mask').hide()
      if (!(userInfo.survey || userInfo.level > 0)) {
        // 没有问卷调查 弹问卷调查
        $('.user-info').hide()
        $('.class-time').hide()
        $('.survey').show()
        $('.mask').show()
      }
    }
  })

  // 提交问卷调查
  $('#submitSurvey').off('click').on('click', e => {
    console.log(userInfo)
    const answer1 = parseInt($(`input[name="in-school"]:checked`).val())
    const answer2 = parseInt($(`input[name="out-school"]:checked`).val())
    const {nickname, birthday, gender} = userInfo
    account.ajax({
      type: 'POST',
      path: `/s/surveys`,
      data: {
        nickname,
        birthday,
        gender,
        answer1,
        answer2
      },
      success: result => {
        console.log(result)
        $('.user-info').hide()
        $('.class-time').hide()
        $('.survey').hide()
        $('.mask').hide()
      },
      error: err => {
        const error = JSON.parse(err.response)
        console.error(error.message)
      }
    })
  })

  setShare()
})

function setShare () {
  window.wxconfig = new WxConfig(wechatConfig, '')
  window.shareFlag = ''
  const userInfo = JSON.parse(window.localStorage.getItem('QKidsUserInfo'))
  if (userInfo && userInfo.shareFlag) window.shareFlag = userInfo.shareFlag
  if (utils.isWeChat()) wxconfig.activeShare(shareFlag, '', {
    title: '【Qkids久趣】4-12岁，在家跟北美外教学英语，新用户100元体验！',
    desc: '严选北美外教在线授课，创造趣味十足的课堂体验，让孩子爱学更有效。',
    link: `${window.location.protocol}//${window.location.host}/wx${Math.ceil(Math.random() * 100)}?_r=${shareFlag}`,
    imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png'
  })
}